package com.gitee.poi.plugin.core;


import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取excel sheet页有效单元格行数
 * @author wangxin
 * @time 2018/11/1 15:39
 */
public class DefaultHandlerSheetLastRow implements HandlerSheetLastRow {

    private static final Logger logger = LoggerFactory.getLogger(DefaultHandlerSheetLastRow.class);

    @Override
    public int getLastRow(Sheet sheet) {
        int lastRowNum = sheet.getLastRowNum();
        int maxRow = lastRowNum;
        for (int rowIndex = 0; rowIndex <= lastRowNum; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                maxRow = rowIndex - 1;
                logger.warn("第"+(rowIndex+1)+"行，已经为空行，取得实际行数"+rowIndex+"行，Sheet原始行数"+(lastRowNum+1)+"行");
                break;
            } else {
                int cellNum = row.getFirstCellNum();
                if(cellNum == -1){ //-1表示空行
                    maxRow = rowIndex - 1;
                    logger.warn("第"+(rowIndex+1)+"行，没有包含任何列，取得实际行数"+rowIndex+"行，Sheet原始行数"+(lastRowNum+1)+"行");
                    break;
                }
                if(cellNum > 0){ //-1表示空行
                    maxRow = rowIndex - 1;
                    logger.warn("第"+(rowIndex+1)+"行，第1列已经为空列，第"+(cellNum+1)+"列才不为空（已抛弃），取得实际行数"+rowIndex+"行，Sheet原始行数"+(lastRowNum+1)+"行");
                    break;
                }
                if (row.getCell(0).getCellType() == CellType.BLANK) {
                    maxRow = rowIndex - 1;
                    logger.warn("第"+(rowIndex+1)+"行，第1列已经为空值，取得实际行数"+rowIndex+"行，Sheet原始行数"+(lastRowNum+1)+"行");
                    break;
                }
            }
        }
        return maxRow;
    }
}
